import { ServerGetAppInfo } from "@go/app/ServerApp";
import { EventsOn } from "@runtime";
import { Button, Modal, Spin, message, notification } from "antd";
import { useEffect } from "react";
import { http } from "./constant/status";
import { initGlobal, useMainStore } from "./store/mainStore";
import { useShallow } from "zustand/react/shallow";
import {
  CheckStartIsUpdate,
  GetAppVersion,
  StartUpdate,
} from "@go/app/UpdateApp";

const BeforeHandle = (props: { children: React.ReactNode }) => {
  const [api, contextHolder] = notification.useNotification();
  const {
    appLoading,
    appInfo,
    initApp,
    initSetting,
    initialSettingFormValues,
  } = useMainStore(
    useShallow((state) => ({
      appLoading: state.appLoading,
      appInfo: state.appInfo,
      initApp: state.initApp,
      initSetting: state.initSetting,
      initialSettingFormValues: state.initialSettingFormValues,
    }))
  );
  async function getAppInfo() {
    const res = await ServerGetAppInfo();
    if (res.code === http.StatusOK) {
      useMainStore.setState({
        appInfo: {
          ...appInfo,
          ...res.data,
          app_name: res.data.app_name || "小助手",
        },
        initApp: true,
      });
    }
  }

  useEffect(() => {
    getAppInfo();
    async function init() {
      const res = await CheckStartIsUpdate();
      if (res) {
        Modal.success({
          title: "更新提醒",
          content: "应用已完成更新(*^▽^*)",
        });
      }
    }
    init();
    initGlobal();
  }, []);

  // 检查更新
  const checkUpdate = async () => {
    try {
      const res = await GetAppVersion(
        appInfo.download_url,
        appInfo.pwd,
        appInfo.file_index
      );
      if (res.code !== http.StatusOK) {
        return;
      }
      if (Number(res.data?.new_version) <= Number(appInfo.version)) {
        return;
      }
      api.open({
        message: "有可用新版本",
        description: (
          <div>{`新版本(v${res.data?.new_version})，是否立即下载？`}</div>
        ),
        placement: "bottomRight",
        duration: 6,
        btn: (
          <>
            <Button type="link" size="small" onClick={() => api.destroy()}>
              忽略
            </Button>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const res = await StartUpdate();
                if (res.code !== http.StatusOK) {
                  message.error(res.msg);
                }
              }}
            >
              下载
            </Button>
          </>
        ),
      });
    } catch (err) {
      message.error(String(err));
    }
  };

  // 偏好设置初始化完成后，判断是否要检查更新
  useEffect(() => {
    if (initSetting && initApp) {
      if (initialSettingFormValues.auto_check_update) {
        checkUpdate();
      }
    }
  }, [initApp, appInfo, initSetting, initialSettingFormValues]);

  // 全局事件监听
  useEffect(() => {
    EventsOn("errorMsg", (msg: string) => {
      message.error(msg, 3);
    });
    EventsOn("successMsg", (msg: string) => {
      message.success(msg);
    });
  }, []);

  return (
    <Spin spinning={appLoading}>
      {contextHolder}
      {props.children}
    </Spin>
  );
};

export default BeforeHandle;
